package com.weijing.pretty_app.dialog

import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.LoadingViewBinding
import com.weijing.pretty_app.util.KeyUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LoadingDialog(var message: String? = null) : DialogFragment() {

    private lateinit var binding: LoadingViewBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?,
    ): View {
        binding = LoadingViewBinding.inflate(inflater, container, false)

        dialog?.window?.apply {
            setBackgroundDrawable(ColorDrawable(resources.getColor(R.color.color_90000)))
            setDimAmount(0f)
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (!message.isNullOrEmpty()) {
            binding.loadingViewTvContent.text = message
        }

        // 监听关闭事件
        LiveEventBus.get<Boolean>(KeyUtil.CLOSE_LOADING)
            .observe(viewLifecycleOwner) { shouldClose ->
                if (shouldClose && (isVisible || isResumed)) {
                    dismissSafe()
                } else {
                    viewLifecycleOwner.lifecycleScope.launch {
                        delay(2000)
                        dismissSafe()
                    }
                }
            }
    }

    override fun onStart() {
        super.onStart()
        isCancelable = true    //点击外部不可取消
        val dm = DisplayMetrics()
        this.activity?.windowManager?.defaultDisplay?.getMetrics(dm)
        this.dialog?.window?.setLayout(dm.widthPixels, dm.heightPixels)
    }

    private fun dismissSafe() {
        if (parentFragmentManager.isStateSaved) {
            // 延迟直到状态恢复再执行关闭
            parentFragmentManager.beginTransaction()
                .remove(this)
                .commitAllowingStateLoss()
        } else {
            dismiss()
        }
    }
}

open class ShowLoadingDialog {

    fun showing(manager: FragmentManager, message: String? = null) {
        if (manager.isStateSaved) {
            manager.beginTransaction()
                .add(LoadingDialog(message), "loadingDialog")
                .commitAllowingStateLoss()
        } else {
            val tag = manager.findFragmentByTag("loadingDialog")
            if (tag == null) {
                LoadingDialog(message).show(manager, "loadingDialog")
            }
        }
    }

    fun closeDialog(manager: FragmentManager) {
        val fragment = manager.findFragmentByTag("loadingDialog")
        if (fragment is DialogFragment) {
            if (fragment.isAdded && !manager.isStateSaved) {
                fragment.dismiss()
            } else {
                fragment.dismissAllowingStateLoss()
            }
        }
    }
}